package jblip.gui.components.view;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.Observable;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import jblip.gui.data.images.ImageChangeListener;
import jblip.resources.Update;

public class UpdateChannelPanel extends ChannelViewPanel<Update> implements
    ImageChangeListener {
  public static int INITIAL_SIZE = 15;

  private final JPanel updates_panel;

  public UpdateChannelPanel() {
    super();

    final BoxLayout layout = new BoxLayout(this, BoxLayout.X_AXIS);
    this.setLayout(layout);

    updates_panel = new JPanel();
    updates_panel.setOpaque(false);
    updates_panel.setLayout(new BoxLayout(updates_panel, BoxLayout.Y_AXIS));

    this.add(Box.createHorizontalGlue());
    this.add(updates_panel);
    this.add(Box.createHorizontalGlue());

    this.repaint();
  }

  private static final long serialVersionUID = 1L;

  @Override
  public void update(final Observable o, final Object arg) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        if (arg instanceof Iterable<?>) {
          for (Object obj : (Iterable<?>) arg) {
            addUpdateComponent((Update) obj);
          }
          updates_panel.repaint();
          UpdateChannelPanel.this.setSize(getPreferredSize());
        }
      }
    });
  }
  
  private void addUpdateComponent(final Update update) {
    updates_panel.add(new UpdateComponent(update), 0);
    updates_panel.add(Box.createVerticalStrut(5), 1);
  }

  @Override
  public synchronized void imageChange(final Image bg) {
    this.bgimage = bg;
    invalidate();
    repaint();
  }

  private synchronized void paintBackground(final Graphics g) {
    if (bgimage != null && bgimage.getWidth(this) != -1
        && bgimage.getHeight(this) != -1 && isShowing()) {
      final Rectangle screen = getVisibleRect();
      int next_w = 0;
      int next_h = 0;
      while (next_h < screen.height) {
        g.drawImage(bgimage, screen.x + next_w, screen.y + next_h, this);
        next_w += bgimage.getWidth(this);
        if (next_w > screen.width) {
          next_h += bgimage.getHeight(this);
          next_w = 0;
        }
      }
    }
  }
  
  @Override
  protected void paintComponent(final Graphics g) {
    paintBackground(g);
    super.paintComponent(g);
  }
}
